package com.piece.admin.config;

import com.piece.core.oauth.config.CustomWebSecurityConfig;
import com.piece.core.oauth.config.WebSecurityProvider;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import java.util.Comparator;
import java.util.List;

@Configuration
@EnableWebSecurity
public class UaaSecurityConfiguration extends CustomWebSecurityConfig implements InitializingBean {

    @Autowired(required = false)
    private List<WebSecurityProvider> providers;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);

        if (null != providers) {
            for (WebSecurityProvider provider : providers) {
                provider.configure(auth);
            }
        }
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //super.configure(web);

        if (null != providers) {
            for (WebSecurityProvider provider : providers) {
                provider.configure(web);
            }
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        if (null != providers) {
            for (WebSecurityProvider provider : providers) {
                provider.configure(http);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (null != providers) {
            providers.sort(Comparator.comparingInt(Ordered::getOrder));
        }
    }
}
